package io.zso.commons.dynamic.datasource.mongo.aspect;

import io.zso.commons.mongodb.config.DynamicMongoFactory;
import io.zso.commons.security.context.TenantContext;
import io.zso.commons.security.user.SecurityUser;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

class DynamicMongoDataSourceAdvice implements MethodInterceptor {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public Object invoke(MethodInvocation point) throws Throwable {
        String tenantCode = TenantContext.getTenantCode(SecurityUser.getUser());
        //无租户直接跳过
        if (StringUtils.isEmpty(tenantCode)) {
            return point.proceed();
        }
        //有租户指定数据源
        try {
            //设置租户MongoDB数据源
            DynamicMongoFactory.setDatabaseNameForCurrentThread(tenantCode);
            logger.debug("set mongo datasource is {}", tenantCode);

            return point.proceed();
        } finally {
            //清除租户MongoDB数据源
            DynamicMongoFactory.clearDatabaseNameForCurrentThread();
            logger.debug("clean mongo datasource {}", tenantCode);
        }
    }
}